package com.lanyou.esb.web.serviceChannelManagement;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lanyou.cook.common.Constants;
import com.lanyou.cook.entity.domain.userManagement.User;
import com.lanyou.cook.service.security.UserSessionService;
import com.lanyou.cook.util.gson.GsonUtil;
import com.lanyou.esb.common.CommonUtils;
import com.lanyou.esb.repository.HttpRepository;
import com.lanyou.esb.repository.ServiceChannelManagerRepository;
import com.lanyou.esb.service.ServiceAccessApplicationService;
import com.lanyou.esb.service.VisiblityService;
import com.lanyou.esb.web.param.ChannelSystemParam;
import com.lanyou.esb.web.serviceChannelManagement.vo.ChannelSystemVo;

/**
 * 渠道系统管理控制器
 * 
 * @author Davey.wu
 */
@RestController
@RequestMapping(Constants.BASE_URL_API + "/channelSystemManagement")
public class ChannelSystemManagementController {
	@Autowired
	private VisiblityService visiblityService;
	@Autowired
	private HttpRepository httpRepository;

	@Autowired
	ServiceAccessApplicationService serviceAccessApplicationService;

	@Autowired
	private ServiceChannelManagerRepository serviceChannelManagerRepository;

	@Autowired
	private UserSessionService userSessionService;

	/**
	 * 获取渠道系统信息，分页
	 * 
	 * @param param
	 * @param pageable
	 * @return
	 */
	@RequestMapping("/findInterfaceTokenInfos")
	public Page<ChannelSystemVo> findInterfaceTokenInfos(
			ChannelSystemParam param, Pageable pageable) {
		User user = userSessionService.getCurrentAuthenticatedUser();
		if (user == null) {
			return new PageImpl<ChannelSystemVo>(
					new ArrayList<ChannelSystemVo>(0), pageable, 0);
		}
		if (param.getFieldId() == null) {
			param.setFieldId("");
		}
		if (param.getSystemId() == null) {
			param.setSystemId("");
		}
		if (param.getInterfaceName() == null) {
			param.setInterfaceName("");
		} else {
			param.setInterfaceName("%" + param.getInterfaceName() + "%");
		}
		List<Object> totals = serviceChannelManagerRepository
				.findVisibleTotalNum(param.getFieldId(), param.getSystemId(),
						param.getInterfaceName(), user.getId());
		BigInteger total = null;
		if (totals != null && totals.size() > 0) {
			total = (BigInteger) totals.get(0);
		}

		if (total == null || total.longValue() <= 0) {
			return new PageImpl<ChannelSystemVo>(
					new ArrayList<ChannelSystemVo>(0), pageable, 0);
		}
		List<Object[]> list = serviceChannelManagerRepository.findVisibleInfo(
				param.getFieldId(), param.getSystemId(),
				param.getInterfaceName(), user.getId(),
				pageable.getPageNumber() * pageable.getPageSize(),
				pageable.getPageSize());

		List<ChannelSystemVo> result = new ArrayList<ChannelSystemVo>(
				list.size());
		for (Object[] object : list) {
			ChannelSystemVo vo = new ChannelSystemVo();
			vo.setInterfaceId(object[0] != null ? (String) object[0] : "");
			vo.setSytemId(object[1] != null ? (String) object[1] : "");
			vo.setFieldName(object[2] != null ? (String) object[2] : "");
			vo.setSystemName(object[3] != null ? (String) object[3] : "");
			vo.setInterfaceName(object[4] != null ? (String) object[4] : "");
			// 对系统排序
			vo.setVisibleListName(sort(object[5] != null ? (String) object[5]
					: ""));
			vo.setVisibleListId(object[6] != null ? (String) object[6] : "");

			sort(vo.getVisibleListName());
			result.add(vo);
		}
		Page<ChannelSystemVo> page = new PageImpl<ChannelSystemVo>(result,
				pageable, total.longValue());
		return page;
	}

	/**
	 * 排序
	 * 
	 * @param values
	 */
	private String sort(String values) {
		if (StringUtils.isBlank(values)) {
			return "";
		}
		if (!values.contains(",")) {
			return values;
		}
		String[] strs = values.split(",");
		List<String> list = Arrays.asList(strs);
		list.sort(new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
		});
		String result = list.toString();
		if (result.length() < 2) {
			return result;
		}
		return result.substring(1, result.length() - 1);
	}

	/**
	 * 更新接口可访问列表
	 * 
	 * @param interfaceId
	 * @param systems
	 * @return
	 */
	@RequestMapping(value = "/updateVisibleList", produces = "application/json")
	public String updateVisibleList(String interfaceId, String systems) {
		List<String> list = null;
		if (StringUtils.isNotBlank(systems)) {
			String[] strs = systems.split(",");
			list = new ArrayList<>(strs.length);
			list.addAll(Arrays.asList(strs));
		} else {
			list = new ArrayList<>(0);
		}
		Map<String, Object> map = new HashMap<>();
		try {
			visiblityService.updateVisibleList(interfaceId, list);
			map.put(CommonUtils.MSG_FIELD_RESULT, "1");
		} catch (Exception e) {
			map.put(CommonUtils.MSG_FIELD_RESULT, "0");
			map.put(CommonUtils.MSG_FIELD_MSG, e.getMessage());
		}
		return GsonUtil.getDefaultGson().toJson(map);
	}
}
